package com.monkeygroup.mygoplus.http;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.monkeygroup.mygoplus.MyGoApplication;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/10/21.
 */
public class UploadRequest extends StringRequest {
    private Map<String, String> mParams;
    private MultipartEntity entity = new MultipartEntity();
    private List<File> mFileParts;
    private String mFilePartName;

    /**
     * 单个文件
     *
     * @param url
     * @param errorListener
     * @param responseListener
     * @param filePartName
     * @param file
     * @param params
     */
    public UploadRequest(String url, Map<String, String> params,
                         Response.Listener<String> responseListener,
                         Response.ErrorListener errorListener,
                         String filePartName, File file) {
        super(Method.POST, url, responseListener, errorListener);

        mFileParts = new ArrayList<>();
        if (file != null) {
            mFileParts.add(file);
        }
        mFilePartName = filePartName;
        this.mParams = params;
        buildMultipartEntity();
    }

    /**
     * 多个文件，对应一个key
     *
     * @param url
     * @param errorListener
     * @param responseListener
     * @param filePartName
     * @param files
     * @param params
     */
    public UploadRequest(String url, Map<String, String> params,
                         Response.Listener<String> responseListener,
                         Response.ErrorListener errorListener,
                         String filePartName, List<File> files) {
        super(Method.POST, url, responseListener, errorListener);
        mFilePartName = filePartName;
        mFileParts = files;
        this.mParams = params;
        buildMultipartEntity();
    }

    @Override
    protected Response<String> parseNetworkResponse(
            NetworkResponse response) {
        String parsed;

        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException var4) {
            parsed = new String(response.data);
        }

        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParams;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        if (MyGoApplication.token != null && !MyGoApplication.token.equals("")) {
            Map<String, String> headers = new HashMap<>();
            headers.put("token", MyGoApplication.token);

            return headers;
        } else {
            return super.getHeaders();
        }

    }

    private void buildMultipartEntity() {
        if (mFileParts != null && mFileParts.size() > 0) {
            for (File file : mFileParts) {
                entity.addPart(mFilePartName, new FileBody(file));
            }
            long l = entity.getContentLength();

            VolleyLog.e(mFileParts.size() + "个，长度：" + l);
        }

        try {
            if (mParams != null && mParams.size() > 0) {
                for (Map.Entry<String, String> entry : mParams.entrySet()) {
                    entity.addPart(
                            entry.getKey(),
                            new StringBody(entry.getValue(), Charset
                                    .forName("UTF-8")));
                }
            }
        } catch (UnsupportedEncodingException e) {
            VolleyLog.e("UnsupportedEncodingException");
        }
    }

    @Override
    public String getBodyContentType() {
        return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            entity.writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

}
